//
//  SYComposeTextView.swift
//  SYWeibo
//
//  Created by Eric on 16/7/27.
//  Copyright © 2016年 Eric. All rights reserved.
//

import UIKit

class SYComposeTextView: UITextView {
    // 重写父类已有属性 监听变化
    override var font: UIFont?{
        didSet{
            placeholderLabel.font = font
        }
    }
    // 设置占位文字
    var placeholder: String?{
        didSet{
            placeholderLabel.text = placeholder
        }
    }
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setuoUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
 // MARK: - 设置视图
    private func setuoUI(){
    backgroundColor = UIColor.whiteColor()
        //添加控件
        addSubview(placeholderLabel)
        //设置约束
        //开启系统的约束
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        // MARK: - 以下是系统的约束
        //距离左边 参照 self
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 5))
        //距离上面 参照 self
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        //距离右边  (*注意不能用 Trailing*) 要用 Width
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Width, multiplier: 1, constant: -10))
        // 通过监听系统通知来得到当前textView 的文字改变
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "valueChange", name: UITextViewTextDidChangeNotification, object: nil)
    
    }
    //通知方法
    func valueChange(){
    placeholderLabel.hidden = self.hasText()
    }
    //MARK :  -懒加载控件
    //占位文字
    private lazy var placeholderLabel: UILabel = {
        let lab = UILabel()
        lab.numberOfLines = 0
        lab.textColor = UIColor.grayColor()
        return lab
    }()
}
